package com.buddy.sds.auth.jwt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.buddy.sds.auth.entity.SystemUser;
import com.buddy.sds.auth.jwt.config.JwtAuthConfigProperties;
import com.buddy.sds.auth.jwt.entity.SystemUserToken;
import com.buddy.sds.auth.jwt.mapper.ISystemUserTokenMapper;
import com.buddy.sds.auth.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class JwtTokenManager {

    @Autowired
    private JwtAuthConfigProperties authConfigProperties;

    @Autowired
    private ISystemUserTokenMapper tokenMapper;

    public String generateAndSave(SystemUser user){

        String token = JWTUtil.sign(user.getUserName(), user.getUserPassword(),authConfigProperties.getTokenExipreSeconds());

        SystemUserToken userToken = tokenMapper.selectOne(new LambdaQueryWrapper<SystemUserToken>().eq(SystemUserToken::getTokenUser,user.getUserId()));

        if(userToken == null){

            userToken = new SystemUserToken(null,token,System.currentTimeMillis() + authConfigProperties.getTokenExipreSeconds() * 1000,user.getUserId());
            tokenMapper.insert(userToken);
        }else{
            userToken.setTokenExpireTime(System.currentTimeMillis() + authConfigProperties.getTokenExipreSeconds() * 1000);
            userToken.setTokenToken(token);
            tokenMapper.updateById(userToken);
        }

        return token;

    }

    public String getUserToken(String user_id){

        SystemUserToken userToken = tokenMapper.selectOne(new LambdaQueryWrapper<SystemUserToken>().eq(SystemUserToken::getTokenUser,user_id));

        if(userToken.getTokenExpireTime() > System.currentTimeMillis()){

            return userToken.getTokenToken();
        }

        return null;
    }



}
